package com.csvw.skr.console.service;

import com.csvw.skr.basic.entity.Dealer;
import com.csvw.skr.basic.entity.DealerHelp;
import com.google.common.collect.Lists;
import com.webonn.frame.core.Pagination;
import com.webonn.frame.db.MyDao;
import com.webonn.frame.util.MyStringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.ws.rs.core.MultivaluedMap;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Created by Administrator on 2016/11/22.
 */
@Service
public class DealerService {
    @Autowired
    private MyDao myDao;

    public Pagination queryDealer(int start, int limit, MultivaluedMap<String, String> filter) {
        Pagination p = new Pagination();
        p.setStart(start);
        p.setLimit(limit);
        String sql = "select dealer.pk_code AS code, dealer.shorter, dealer.`name`, dealer.rbo, dealer.commercial, dealer.area, dealer.province, dealer.city," +
                " dealer.address, dealer.county, dealer.contract, dealer.contractPhone, dealer.active, dealer.emphasis, " +
                "rbo. NAME AS rboName, commercial. NAME AS commercialName, area.`name` AS areaName, " +
                // TODO 经销商和商务经理
                // "dealer.businessManager, u. NAME AS businessManagerName, " +
                "(SELECT group_concat(`name`) FROM `csvw_skr_basic_user` WHERE organization = dealer.area and active = true) as businessManagerName, " +
                "(SELECT CONCAT_WS( '||', group_concat(`pk_empno`), group_concat(`name`)) FROM `csvw_skr_basic_user` WHERE job = 112 AND active = true AND dealer.marketingManager LIKE CONCAT('%', pk_empno, '%')) as marketingManager " +
                "from csvw_skr_basic_dealer dealer " +
                "left join csvw_skr_basic_organization rbo on rbo.pk_code = dealer.rbo " +
                "left join csvw_skr_basic_organization commercial on commercial.pk_code = dealer.commercial " +
                "left join csvw_skr_basic_organization area on area.pk_code = dealer.area " +
                // TODO 经销商和商务经理
                // "left join csvw_skr_basic_user u on u.pk_empno = dealer.businessManager " +
                "where dealer.active =true ";
        List<Object> paramsList = Lists.newArrayList();

        String search = filter.getFirst("search");
        if (!MyStringUtil.isNullOrEmpty(search)) {
            sql += " and CONCAT_WS(',', rbo, commercial, area, dealer.pk_code, dealer.name, area.`name`,commercial.name,rbo.name) like ? ";
            paramsList.add("%" + search.trim() + "%");
        }
        sql += " order by dealer.created desc ";
        return myDao.queryResultToMapPagination(sql, p, paramsList.toArray());
    }

    public Dealer addDealer(Dealer dealer) {
        Date addTime = new Date();
        dealer.setCreated(addTime);
        dealer.setUpdated(addTime);
        dealer.setActive(true);
        myDao.persist(new DealerHelp(dealer, "新增"));
        return myDao.persist(dealer);
    }

    public Dealer updateDealer(Dealer dealer) {
        Dealer entity_old = getDealer(dealer.getCode());
        dealer.setCreated(entity_old.getCreated());
        dealer.setActive(entity_old.isActive());
        dealer.setUpdated(new Date());

        if (myDao.get(dealer.getCode(), DealerHelp.class) == null)
            if (this.isUpdateDealerRelation(entity_old, dealer))
                myDao.persist(new DealerHelp(entity_old, "修改"));

        return myDao.persist(dealer);
    }

    public Dealer getDealer(String id) {
        return myDao.get(id, Dealer.class);
    }

    public Dealer deleteDealer(String id) {
        Dealer del = myDao.get(id, Dealer.class);
        myDao.persist(new DealerHelp(del, "删除"));
        del.setActive(false);
        return myDao.persist(del);
    }

    /**
     * 是否满足更新经销商对应关系需求
     * 判断是否更新了rbo，commercial，area，businessManager
     *
     * @return true 更新了 false 没更新
     */
    private boolean isUpdateDealerRelation(Dealer oldDealer, Dealer newDealer) {
        boolean b = Objects.nonNull(oldDealer.getRbo())
                && Objects.nonNull(oldDealer.getCommercial())
                && Objects.nonNull(oldDealer.getArea())
                && Objects.nonNull(oldDealer.getShorter());

        return b && (!oldDealer.getRbo().equals(newDealer.getRbo())
                || !oldDealer.getCommercial().equals(newDealer.getCommercial())
                || !oldDealer.getArea().equals(newDealer.getArea())
                || !oldDealer.getShorter().equals(newDealer.getShorter())
        );
    }


    /**
     * 返回需要更新对应关系的经销商数
     *
     * @return
     */
    public int getUpDealerRelationNumber() {
        String sql = "SELECT COUNT(pk_code) FROM csvw_skr_basic_dealer_help";
        BigInteger bigInteger = (BigInteger) myDao.uniqueResult(sql, new Object[]{});
        return bigInteger.intValue();
    }

    /**
     * 获取需要 更新对应关系的经销商 的经销商代码
     */
    public String getUpDealerRelationStr() {
        // 获取需要 更新对应关系的经销商 的经销商代码
        String sql = "select pk_code from csvw_skr_basic_dealer_help";
        List<String> dealerCodelist = myDao.listIds(sql, new Object[]{});

        return String.join(",", dealerCodelist);

    }

    /**
     * 经销商对应关系更新成功 删除表帮助表中经销商代码
     *
     * @return
     */
    public boolean deleteDealerRelation() {
        return myDao.executeSQLUpdate("delete from csvw_skr_basic_dealer_help ");
    }


    /**
     * 更新经销商对应关系
     *
     * @param dealerCodeStr 需要更新的经销商代码str，逗号分割
     * @return
     */
    public boolean updateDealerRelation(String dealerCodeStr) {
        if (dealerCodeStr.isEmpty())
            return true;

        String handleSql = "call p_update_dealer_relation(?)";

        List<Map<String, Object>> list = myDao.queryResultToMap(handleSql, new Object[]{dealerCodeStr});

        return Objects.nonNull(list) && list.size() != 0 && (Integer) list.get(0).get("t_error") == 0;
    }

    public List<Map<String, Object>> listDealerByMarketingManager(String empno) {
        String dealer_sql = "select dealer.pk_code as code, dealer.shorter as name from csvw_skr_basic_dealer dealer " +
                "where dealer.active = true and dealer.marketingManager like ? ";
        List<Map<String, Object>> dealers = myDao.queryResultToMap(dealer_sql, new Object[]{"%" + empno + "%"});
        return dealers;
    }
}
